package Service;


import org.hibernate.Session;
import org.hibernate.Transaction;

import DAO.userDAO;
import Form.RegisterUserForm;
import HibernateUtilsforBM.SFactoryGenerator;
import Model.user;
/**
 * 用户业务管理
 * @author MacBook
 *
 */
public class userService {
	//登录服务
	public user LoginService(String username,String password){
		Session session = SFactoryGenerator.getSession();
		//开启事务
		Transaction tx = session.beginTransaction();
		user u = null;
		try{
				u = userDAO.FindbyNameAndPassword(session, username, password);
				tx.commit();
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				tx.rollback();
			}finally{
				session.close();
			}
		return u;
	}
	//注册服务
	public user RegisterService(RegisterUserForm register){
		user registerUser = null;
		//开启事务之前先验证
		if(register.getUsername().length() <3 || register.getUsername().length() >12 || 
				register.getPassword().length()<6 || register.getPassword().length()>20)
			return registerUser;
		
		Session session = SFactoryGenerator.getSession();
		
		//开启事务
		Transaction tx = session.beginTransaction();
		try{
			user u = userDAO.findByUsername(session,register.getUsername());
			if(u == null)
			{
				//注册信息copy
				registerUser = new user();
				registerUser.setUsername(register.getUsername());
				registerUser.setPassword(register.getPassword());
				registerUser.setemail(register.getEmail());
				register.setTel(register.getTel());
				userDAO.save(session,registerUser);
				
			}
			tx.commit();
		}catch (Exception e) {
			// TODO: handle exception
			System.err.println("出现错误！");
			tx.rollback();
		}finally {
			session.close();
		}
		
		return registerUser;
	}
	//是否存在用户
	public boolean veriUser(String username){
		Session session = SFactoryGenerator.getSession();
		boolean exist = false;
		//开启事务
		Transaction tx = session.beginTransaction();
		try{
			user u = userDAO.findByUsername(session, username);
			if(u != null)
				exist = true;
		}catch (Exception e) {
			// TODO: handle exception
			tx.rollback();
		}finally {
			session.close();
		}
		return exist;
	}
	//寻找用户信息
	public user findUserMsg(String username,String email,String tel){
		Session session = SFactoryGenerator.getSession();
		user u = null;
		Transaction tx = session.beginTransaction();
		try {
			 u = userDAO.findByMessages(session, username, email, tel);
			 tx.commit();
		} catch (Exception e) {
			// TODO: handle exception
			tx.rollback();
		}
		return u;
	}
	//修改密码
	public void alterUserPassword(String username,String password){
		Session session = SFactoryGenerator.getSession();
		Transaction tx = session.beginTransaction();
		try {
			 userDAO.updatePasswordByUsername(session, username, password);
			 tx.commit();
		} catch (Exception e) {
			// TODO: handle exception
			tx.rollback();
		}
	}
}
